<template>
    <div class="edu-page-warp">
        <div class="left-part-box">
            <div
                v-for="(menu, index) in menuTreeTypeOpt.data"
                :key="menu.index"
                class="menus-collapse-wrap"
            >
                <el-collapse v-model="menuTreeTypeOpt.value" class="menus-collapse" accordion>
                    <el-collapse-item :title="menu.name" :name="menu.value">
                        <el-button type="text" size="mini" @click="() => addAuthorityMenu()">
                            {{ $t('message.add') }}
                        </el-button>
                        <el-tree
                            :data="menuTree[index]"
                            :props="defaultProps"
                            :expand-on-click-node="false"
                            :highlight-current="true"
                            @node-click="nodeClick"
                        >
                            <span slot-scope="{ node, data }" class="custom-tree-node">
                                <span :title="node.label">{{ getLabelStr(node.label) }}</span>
                                <span>
                                    <el-button
                                        v-if="data.type == 1"
                                        type="text"
                                        size="mini"
                                        @click="() => addAuthorityMenu(node, data)"
                                    >
                                        {{ $t('message.add') }}
                                    </el-button>
                                    <el-button
                                        type="text"
                                        size="mini"
                                        @click="() => deleteMenu(node, data)"
                                    >
                                        {{ $t('message.delete') }}
                                    </el-button>
                                </span>
                            </span>
                        </el-tree>
                    </el-collapse-item>
                </el-collapse>
            </div>
            <!-- <div style="padding: 8px;" class="bg-white">
        <p class="tree-title">
          <span>同济大学</span>
          <el-button type="text" size="mini" @click="() => deleteMenu()">{{$t('message.delete')}}</el-button>
          <el-button type="text" size="mini" @click="() => addAuthorityMenu()">{{$t('message.add')}}</el-button>
        </p>
      </div> -->
        </div>
        <div class="right-part-box">
            <el-card shadow="never">
                <div class="edu-page-title">
                    {{ menuTreeTypeOpt.data[currentMenuType - 1].name }}层级明细
                </div>
                <el-row class="bg-white search-bar">
                    <el-col :span="8">
                        <KeywordInput
                            v-model="queryMenuForm.name"
                            placeholder="菜单名称"
                            @enter="queryMenus(true)"
                        />
                    </el-col>
                    <div class="float-right">
                        <el-button type="primary" @click="queryMenus(true)">
                            {{ $t('message.filter') }}
                        </el-button>
                        <!-- 排序暂时隐藏 -->
                        <el-button @click="openOrderDialog">排序</el-button>
                        <!-- <el-button type="primary" @click="addRootDept(-1)">{{$t('message.add')}}</el-button> -->
                    </div>
                </el-row>
                <el-row>
                    <el-col>
                        <edu-table
                            :data="menus"
                            :total="queryMenuForm.total"
                            :selection="false"
                            :order="false"
                            :max-height="500"
                            @page-change="handleSizeChange"
                            :key="tableKey"
                        >
                            <el-table-column
                                label="菜单中文名称"
                                prop="authNameCh"
                                show-overflow-tooltip
                                min-width="100px"
                            />
                            <el-table-column
                                label="菜单英文名称"
                                prop="authNameEn"
                                show-overflow-tooltip
                                min-width="100px"
                            />
                            <!-- <el-table-column label="父ID" prop="parentAuthId"/> -->
                            <el-table-column label="url路径" show-overflow-tooltip prop="urlPath" />
                            <el-table-column
                                label="权限编码"
                                show-overflow-tooltip
                                prop="authCode"
                            />
                            <el-table-column label="类型">
                                <template slot-scope="scope">
                                    {{ scope.row.type | menuType }}
                                </template>
                            </el-table-column>
                            <el-table-column label="排序" prop="orderNo" />
                            <el-table-column label="操作" width="100">
                                <template slot-scope="scope">
                                    <el-button type="text" @click="editMenu(scope.row.authId)">
                                        {{ $t('message.edit') }}
                                    </el-button>
                                    <el-button
                                        type="text"
                                        @click="
                                            deleteMenuByRow(scope.row.authId, scope.row.roleType)
                                        "
                                    >
                                        {{ $t('message.delete') }}
                                    </el-button>
                                </template>
                            </el-table-column>
                        </edu-table>
                    </el-col>
                </el-row>
            </el-card>
        </div>
        <edu-dialog
            ref="addDialog"
            :title="dialogTitle"
            size="small"
            width="700"
            class="systemDialog"
            @close="resetAddForm"
            @confirm="submitMenuForm"
        >
            <el-form
                ref="createMenuForm"
                :model="createMenuForm"
                label-suffix="：" 
                label-position="right" 
                :rules="rules"
                label-width="130px"
            >
                <el-row>
                    <el-form-item label="菜单中文名称" prop="authNameCh">
                            <el-input v-model="createMenuForm.authNameCh" />
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item label="菜单英文名称" prop="authNameEn">
                        <el-input v-model="createMenuForm.authNameEn" />
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item  prop="parentAuthId">
                        <el-tooltip slot="label"  class="item" effect="dark" content="当前菜单的父菜单的ID值" placement="top-start">
                            <span>父ID<i class="el-icon-question"></i>：</span>
                        </el-tooltip>
                        <el-input v-model="createMenuForm.parentAuthId" readonly />
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item  prop="urlPath">
                        <el-tooltip slot="label"  class="item" effect="dark" content="当前菜单跳转的页面地址" placement="top-start">
                            <span>url路径<i class="el-icon-question"></i>：</span>
                        </el-tooltip>
                        <el-input v-model="createMenuForm.urlPath" />
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item  prop="authCode">
                        <el-tooltip slot="label"  class="item" effect="dark" content="当前菜单对应的图标地址" placement="top-start">
                            <span>权限编码<i class="el-icon-question"></i>：</span>
                        </el-tooltip>
                        <el-input v-model="createMenuForm.authCode" />
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item label="菜单类型" prop="type">
                        <el-select v-model="createMenuForm.type" style="width: 100%;">
                            <el-option
                                v-for="item in typeList"
                                :key="item.value"
                                :label="item.value | menuType"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-row>
                <el-row v-if="createMenuForm.type==2">
                    <el-form-item label="请求方式" prop="reqMethod">
                        <el-tooltip slot="label"  class="item" effect="dark" content="当前按钮下接口的请求方式" placement="top-start">
                            <span>请求方式<i class="el-icon-question"></i>：</span>
                        </el-tooltip>
                        <el-select v-model="createMenuForm.reqMethod" style="width: 100%;">
                            <el-option
                                v-for="item in methodList"
                                :key="item.value"
                                :label="item.value"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-row>
                <el-row v-if="createMenuForm.type==2">
                    <el-form-item label="请求接口" prop="interfaceUrl">
                        <el-tooltip slot="label"  class="item" effect="dark" content="当前按钮下接口的请求路径 例如：/userGroup/addGroup" placement="top-start">
                            <span>请求接口<i class="el-icon-question"></i>：</span>
                        </el-tooltip>
                        <el-input v-model="createMenuForm.interfaceUrlPath" />
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item  prop="application">
                        <el-tooltip slot="label"  class="item" effect="dark" content="当前菜单url地址对应的后端微服务名称" placement="top-start">
                            <span>菜单应用<i class="el-icon-question"></i>：</span>
                        </el-tooltip>
                        <el-input v-model="createMenuForm.application" />
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item label="菜单顺序" prop="orderNo">
                        <el-input v-model="createMenuForm.orderNo" />
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item  prop="iconPath">
                        <el-tooltip slot="label"  class="item" effect="dark" content="当前菜单对应的首页快捷通道的图标地址" placement="top-start">
                            <span>图标地址<i class="el-icon-question"></i>：</span>
                        </el-tooltip>
                        <el-input v-model="createMenuForm.iconPath" />
                    </el-form-item>
                </el-row>

                <el-row>
                    <el-form-item v-if="currentMenuType === 1" label="管理部门" prop="mgerDeptId">
                        <el-select
                            v-model="createMenuForm.mgerDeptId"
                            :disabled="departmentIsDisabled"
                            style="width: 100%;"
                        >
                            <el-option
                                v-for="item in departmentList"
                                :key="item.value"
                                :label="item.name"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-row>
            </el-form>
        </edu-dialog>

        <edu-dialog
            ref="orderDialog"
            :title="$t('排序')"
            :auto-height="true"
            size="small"
            class="systemDialog"
            @confirm="updateOrder"
        >
            <!-- 原版 -->
            <div class="edu-page-title">{{ currentMenuTypeName }}</div>
            <el-tree
                :data="orderMenuTree"
                :props="defaultProps"
                :expand-on-click-node="false"
                draggable
            />
            <!-- <div v-for="(tree,index) in orderMenuTree" :key="index">
        <div class="edu-page-title">{{ menuTreeTypeOpt.data[index] }}</div>
        <el-tree :data="tree" :props="defaultProps" draggable
            :expand-on-click-node="false" >
        </el-tree>
      </div> -->
        </edu-dialog>
    </div>
</template>

<script>
const defaultCreateForm = {
    authNameCh: '',
    authNameEn: '',
    parentAuthId: '',
    urlPath: '',
    authCode: '',
    type: '',
    orderNo: '',
    application: '',
    iconPath:'',
    mgerDeptId: '',
    roleType: 1,
    reqMethod:'',
    interfaceUrlPath:''
}
import {
    getAuthorities,
    findMenuListPage,
    deleteAuthorityMenu,
    orderMenus,
    addAuthorityMenu,
    updateAuthorityMenu,
    findMeunById
} from 'common/src/api/user'
import UTILS from 'common/src/utils/utils'

export default {
    name: 'Menus',
    filters: {
        menuType: function(value) {
            if (!value) {
                return ''
            }
            value = value.toString()
            return value == '1' ? '菜单' : '按钮'
        }
    },
    data() {
        var validateMenuName = (rule, value, callback) => {
            var regex = /^[\w\d\s\S\u4e00-\u9fa5]{1,255}$/
            if (regex.test(value)) {
                callback()
            } else {
                callback(
                    new Error(
                        UTILS.i18nReplace(this.$t('system.errorTipInfo'), {
                            minLength: 1,
                            maxLength: 255
                        })
                    )
                )
            }
        }
        return {
            queryMenuForm: {
                // authNameCh: "",
                name: '', // 修改bug2002（同后台沟通传参不对修改authNameCh改为name）
                total: 0,
                pageNum_: 1,
                pageSize_: 20,
                roleType: 1
            },
            type: '',
            typeList: [{ value: 1 }, { value: 2 }],
            methodList:[{value:'get'},{value:'post'},{value:'put'},{value:'delete'}],
            parentMgerDeptId: '',
            departmentIsDisabled: false,
            departmentList: [
                {
                    name: '···',
                    value: '0'
                },
                {
                    name: '本科生',
                    value: '1'
                },
                {
                    name: '研究生',
                    value: '2'
                }
            ],
            isEdit: false,
            dialogTitle: '',
            menuTree: [],
            orderMenuTree: [],
            currentMenuTypeName: '',
            allMenus: [],
            menus: [],
            pickedDepts: [],
            defaultProps: {
                children: 'children',
                label: 'authNameCh'
            },
            createMenuForm: UTILS.clone(defaultCreateForm),
            rules: {
                authNameCh: [
                    {
                        required: true,
                        message: '请输入菜单中文名称',
                        trigger: 'blur'
                    },
                    {
                        validator: validateMenuName,
                        trigger: 'blur'
                    }
                ],
                authNameEn: [
                    {
                        required: true,
                        message: '请输入菜单英文名称',
                        trigger: 'blur'
                    },
                    {
                        validator: validateMenuName,
                        trigger: 'blur'
                    }
                ],
                type: [
                    {
                        required: true,
                        message: '请选择菜单类型',
                        trigger: 'blur'
                    }
                ],
                mgerDeptId: [
                    {
                        required: true,
                        message: '请选择管理部门',
                        trigger: 'blur'
                    }
                ]
            },
            menuTreeTypeOpt: {
                value: 1,
                data: [
                    {
                        name: '管理员菜单',
                        value: 1
                    },
                    {
                        name: '教师菜单',
                        value: 2
                    },
                    {
                        name: '学生菜单',
                        value: 3
                    }
                ]
            },
            currentMenuType: 1,
            tableKey: 1 
        }
    },
    watch: {
        'menuTreeTypeOpt.value'(newVal) {
            if (newVal) {
                if (newVal !== this.currentMenuType) {
                    // 切换角色菜单，改变key值，table表重新渲染
                    this.tableKey = new Date().getTime();
                    this.queryMenuForm = {
                        name: '',
                        total: 0,
                        pageNum_: 1,
                        pageSize_: 20,
                        roleType: 1
                    }
                    this.queryMenuForm.roleType = newVal
                    this.queryMenus()
                    this.currentMenuType = newVal
                }
            }
        }
    },
    created() {},
    mounted() {
        this.showMenuTree()
        this.queryMenus()
    },
    methods: {
        getLabelStr(str) {
            if (!str) {
                return ''
            } else {
                return str.length > 10 ? str.substring(0, 10).concat('...') : str
            }
        },
        nodeClick(data) {
            this.queryMenuForm.parentAuthId = data.authId
            this.queryMenus(true)
        },
        handleSizeChange(data) {
            this.queryMenuForm.pageSize_ = data.pageSize
            this.queryMenuForm.pageNum_ = data.pageNum
            this.queryMenus()
        },
        submitMenuForm() {
            this.$refs.createMenuForm.validate(valid => {
                let _promise = null
                let message = this.$t('message.addSuccess')
                if (valid) {
                    if (this.isEdit) {
                        message = this.$t('message.editSuccess')
                        _promise = updateAuthorityMenu(this.createMenuForm)
                    } else {
                        _promise = addAuthorityMenu(this.createMenuForm)
                    }
                    _promise.then(() => {
                        this.$message({
                            type: 'success',
                            message: message
                        })
                        this.$refs.addDialog.close()
                        this.queryMenuForm.roleType = this.createMenuForm.roleType
                        this.queryMenus(true)
                        this.showMenuTree()
                    })
                }
            })
        },
        editMenu(authId) {
            findMeunById(authId).then(rsp => {
                this.createMenuForm = rsp.data
                let mgerDeptIdTemp = rsp.data.mgerDeptId
                if (this.createMenuForm.parentAuthId === -1) {
                    this.createMenuForm.mgerDeptId = mgerDeptIdTemp
                    this.departmentIsDisabled = true
                } else {
                    findMeunById(this.createMenuForm.parentAuthId).then(resp => {
                        this.parentMgerDeptId = resp.data && resp.data.mgerDeptId
                        this.createMenuForm.mgerDeptId =
                            this.parentMgerDeptId !== '0' && this.parentMgerDeptId !== ''
                                ? this.parentMgerDeptId
                                : mgerDeptIdTemp
                                ? mgerDeptIdTemp
                                : ''
                        this.departmentIsDisabled = this.createMenuForm.mgerDeptId ? true : false
                    })
                }
                this.isEdit = true
                this.dialogTitle = this.$t('message.edit')
                this.$refs.addDialog.open()
            })
        },
        resetAddForm() {
            this.$refs.createMenuForm.clearValidate()
            this.createMenuForm = UTILS.clone(defaultCreateForm)
        },
        deleteMenuByRow(authId, roleType) {
            let hasChild = this.allMenus.some(item => {
                return item.parentAuthId == authId
            })
            if (hasChild) {
                this.$message({
                    type: 'warning',
                    message: '该菜单存在子菜单, 不可删除.'
                })
                return
            }
            this.$delConfirm('此操作将会永久删除该菜单, 是否继续').then(() => {
                this._deleteMenu([authId], roleType)
            })
        },
        deleteMenu(node, data) {
            if (node.childNodes.length > 0) {
                this.$message({
                    type: 'warning',
                    message: '该菜单存在子菜单, 不可删除.'
                })
                return
            }
            this.$delConfirm('此操作将会永久删除该菜单, 是否继续').then(() => {
                this._deleteMenu(data.authId, data.roleType)
            })
        },
        _deleteMenu(authIds, roleType) {
            deleteAuthorityMenu(authIds).then(res => {
                if (res.code == 200) {
                    this.$message({
                        type: 'success',
                        message: this.$t('message.deleteSuccess')
                    })
                    this.queryMenuForm.roleType = roleType
                    this.queryMenus(true)
                    this.showMenuTree()
                }
            })
        },
        addAuthorityMenu(node, data) {
            this.isEdit = false
            this.dialogTitle = this.$t('message.add')
            this.createMenuForm = UTILS.clone(defaultCreateForm)
            if (node && node.data) {
                this.parentMgerDeptId = node.data.mgerDeptId
            } else {
                this.parentMgerDeptId = ''
            }
            if (!data) {
                this.createMenuForm.parentAuthId = -1
                this.createMenuForm.mgerDeptId = ''
            } else {
                this.createMenuForm.parentAuthId = data.authId
                this.createMenuForm.mgerDeptId =
                    this.parentMgerDeptId !== '0' && this.parentMgerDeptId !== ''
                        ? this.parentMgerDeptId
                        : ''
            }
            this.departmentIsDisabled = this.createMenuForm.mgerDeptId ? true : false
            this.createMenuForm.roleType = (data && data.roleType) || this.menuTreeTypeOpt.value
            this.$refs.addDialog.open()
        },
        queryMenus(reset) {
            if (reset) {
                this.queryMenuForm.pageNum_ = 1
                this.queryMenuForm.total = 0
            }
            findMenuListPage(this.queryMenuForm).then(res => {
                if (res.code === 200) {
                    this.menus = res.data.list
                    this.queryMenuForm.total = res.data.total_
                }
            })
        },
        showMenuTree() {
            // getAuthorities({}).then(res => {
            //   if (res.code == 200) {
            //     this.menuTree = this.$utils.listToTree(
            //       "authId",
            //       "parentAuthId",
            //       res.data
            //     );
            //     this.allMenus = res.data;
            //   };
            // });
            let getWardenMenuTree = getAuthorities({
                roleType: 1
            })
            let getTeacherMenuTree = getAuthorities({
                roleType: 2
            })
            let getStudentMenuTree = getAuthorities({
                roleType: 3
            })
            let menuTree = []
            Promise.all([getWardenMenuTree, getTeacherMenuTree, getStudentMenuTree]).then(res => {
                res.forEach(item => {
                    if (item.code === 200) {
                        menuTree.push(this.$utils.listToTree('authId', 'parentAuthId', item.data))
                        this.menuTree = menuTree
                    }
                })
            })
        },
        openOrderDialog() {
            let index = this.menuTreeTypeOpt.value - 1
            this.currentMenuTypeName = this.menuTreeTypeOpt.data[index].name
            this.orderMenuTree = UTILS.clone(this.menuTree[index])
            this.$refs.orderDialog.open()
        },
        updateOrder() {
            const result = []
            this.getAllMenu(this.orderMenuTree, result)
            orderMenus(result).then(() => {
                this.$message({ type: 'success', message: this.$t('message.saveSuccess') })
                this.$refs.orderDialog.close()
                this.showMenuTree()
                this.queryMenus()
            })
        },
        getAllMenu(list, result, parent) {
            list.forEach((element, index) => {
                const node = {
                    orderNo: index + 1,
                    authId: element.authId,
                    roleType: element.roleType
                }
                if (parent) {
                    node.parentAuthId = parent.authId
                }
                result.push(node)
                if (UTILS.isNotEmpty(element.children)) {
                    this.getAllMenu(element.children, result, element)
                }
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.left-part-box,
.right-part-box {
    float: left;
    margin-right: 20px;
}
.left-part-box {
    width: 300px;
    .el-tree {
        min-height: 450px;
    }
}
.right-part-box {
    width: calc(96% - 300px);
    .el-card {
        width: 100%;
        min-height: 450px;
        display: inline-block;
    }
}
.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 4px;
    color: #3f3f3f;
}
.item-title {
    display: block;
    width: 100%;
    height: 32px;
}
.tree-title {
    margin: 0;
    line-height: 28px;
    padding-left: 8px;
    .el-button {
        float: right;
        margin-right: 4px;
    }
}
.menus-collapse-wrap {
    padding-left: 8px;
    margin-bottom: 8px;
    background: #fff;
}
.pl-20 {
    padding-left: 20px;
}
.search-bar {
    padding: 16px 0;
}
</style>
